package com.googlecode.hmvc4gwt.example.hmvcblog.server.repository.blog;

import java.util.List;

import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.googlecode.hmvc4gwt.example.hmvcblog.server.domain.blog.Blog;
import com.googlecode.hmvc4gwt.example.hmvcblog.server.domain.user.User;
import com.googlecode.hmvc4gwt.example.hmvcblog.server.repository.blog.exceptions.BlogNotFoundException;

/**
 * 
 * 
 * @author jens.meiss
 */
@Transactional
public class BlogRepository extends JpaDaoSupport implements IBlogRepository {

	public void addBlog(Blog blog) {
		getJpaTemplate().persist(blog);
	}

	public Blog findByName(String name) throws BlogNotFoundException {

		@SuppressWarnings("unchecked")
		List<Blog> list = getJpaTemplate().findByNamedQuery("Blog.findByName",
				name);

		if (list.size() == 1) {
			return list.get(0);
		} else {

			throw new BlogNotFoundException();
		}

	}

	public void removeBlog(Blog blog) throws BlogNotFoundException {

//		blog = getJpaTemplate().merge(blog);
		getJpaTemplate().remove(blog);

	}

	public Blog findById(int id) throws BlogNotFoundException {

		try {
			
			Blog blog = getJpaTemplate().find(Blog.class, id); 
			
			return blog; 
			
		} catch (Exception e) {
			throw new BlogNotFoundException();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Blog> getListBlogs() {
		return (List<Blog>) getJpaTemplate().findByNamedQuery("Blog.getAll");
	}

	@SuppressWarnings("unchecked")
	public List<Blog> getBlogsOfuser(User user) {
		return (List<Blog>) getJpaTemplate().findByNamedQuery(
				"Blog.blogsOfUser", user);
	}

	public Blog getBlogEdit(int id) throws BlogNotFoundException {
		
//		return (Blog) getJpaTemplate().findByNamedQuery("Blog.getBlogEdit", id);
		
		Blog blog = findById(id); 
		
		return blog;
	}

	public void update(Blog blog) {
		
//		getJpaTemplate().merge(blog);
		getJpaTemplate().flush();
	}

}
